/**
 * 基于位置的餐厅搜索Hook
 * 集成地理位置获取和高德地图API搜索
 */

'use client';
import { useState, useCallback, useEffect } from 'react';
import { useGeolocation } from '@/features/location/useGeolocation';
import { fetchAll } from '@/lib/data';
import type { Restaurant } from '@/lib/types';
import { debounce } from '@/lib/debounce';

interface UseNearbyRestaurantsOptions {
  autoFetch?: boolean; // 是否自动获取位置并搜索
  debounceMs?: number; // 防抖延迟时间
}

interface UseNearbyRestaurantsReturn {
  restaurants: Restaurant[];
  loading: boolean;
  error: string | null;
  locationStatus: string;
  hasLocation: boolean;
  requestLocation: () => void;
  searchNearby: () => void;
  refresh: () => void;
  reset: () => void;
}

export function useNearbyRestaurants(
  options: UseNearbyRestaurantsOptions = {},
): UseNearbyRestaurantsReturn {
  const { autoFetch = false, debounceMs = 500 } = options;

  const {
    status: locationStatus,
    coords,
    error: locationError,
    request: requestLocation,
    reset: resetLocation,
    hasValidCoords,
    isGranted: locationGranted,
  } = useGeolocation();

  const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 搜索餐厅的核心函数
  const searchRestaurants = useCallback(async (longitude?: number, latitude?: number) => {
    setLoading(true);
    setError(null);

    try {
      const results = await fetchAll(longitude, latitude);
      setRestaurants(results);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取餐厅信息失败';
      setError(errorMessage);
      console.error('搜索餐厅失败:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 防抖版本的搜索函数
  const debouncedSearch = useCallback(
    (...args: Parameters<typeof searchRestaurants>) =>
      debounce(searchRestaurants, debounceMs)(...args),
    [searchRestaurants, debounceMs],
  );

  // 基于当前位置搜索
  const searchNearby = useCallback(() => {
    if (hasValidCoords && coords) {
      debouncedSearch(coords.longitude, coords.latitude);
    } else {
      // 没有位置信息时使用默认搜索
      debouncedSearch();
    }
  }, [hasValidCoords, coords, debouncedSearch]);

  // 刷新数据
  const refresh = useCallback(() => {
    if (hasValidCoords && coords) {
      searchRestaurants(coords.longitude, coords.latitude);
    } else {
      searchRestaurants();
    }
  }, [hasValidCoords, coords, searchRestaurants]);

  // 重置所有状态
  const reset = useCallback(() => {
    setRestaurants([]);
    setLoading(false);
    setError(null);
    resetLocation();
  }, [resetLocation]);

  // 当位置获取成功时自动搜索
  useEffect(() => {
    if (locationGranted && hasValidCoords && coords) {
      searchNearby();
    }
  }, [locationGranted, hasValidCoords, coords, searchNearby]);

  // 处理位置获取错误
  useEffect(() => {
    if (locationError) {
      setError(locationError.message);
    }
  }, [locationError]);

  // 自动获取位置
  useEffect(() => {
    if (autoFetch) {
      requestLocation();
    }
  }, [autoFetch, requestLocation]);

  return {
    restaurants,
    loading,
    error,
    locationStatus,
    hasLocation: Boolean(hasValidCoords),
    requestLocation,
    searchNearby,
    refresh,
    reset,
  };
}
